package com.zyw.zhuangdian.controller;

import com.alibaba.fastjson.JSONObject;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.dto.FileDto;
import com.zyw.zhuangdian.pojo.in.FileDtoIn;
import com.zyw.zhuangdian.service.FileService;
import com.zyw.zhuangdian.util.Assert;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import com.zyw.zhuangdian.util.RespUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Slf4j
public class FileController {
    private final FileService fileService;

    @RequestMapping(value = "saveImage",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> saveBase64Image(@RequestBody JSONObject json){
        Assert.hasKeyAndValue(json,"base64File","文件内容不能为空");

        FileDtoIn in = BeanConvertUtil.covertBean(json, FileDtoIn.class);
        Resp<FileDto> resp = fileService.saveBase64Image(in);
        return RespUtil.OK(resp);
    }
    @RequestMapping(value = "saveImages",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> saveBase64Images(@RequestBody JSONObject json){
        Assert.hasKeyAndValue(json,"base64Files","文件内容不能为空");

        FileDtoIn in = BeanConvertUtil.covertBean(json, FileDtoIn.class);
        Resp<List<FileDto>> resp = fileService.saveBase64Images(in);
        return RespUtil.OK(resp);
    }

    @RequestMapping(value = "saveImageFD",method = RequestMethod.POST)
    public ResponseEntity<String> saveFormDataImage(@RequestParam("img") MultipartFile file){
        Assert.notBlank(file.getOriginalFilename(), "文件不能为空");

        Resp<FileDto> resp = fileService.saveFormDataImage(file);
        return RespUtil.OK(resp.getData().getFileName());
    }

    @RequestMapping(value = "listFiles",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> listFiles(@RequestBody JSONObject json){
        FileDtoIn in = BeanConvertUtil.covertBean(json, FileDtoIn.class);
        Resp<List<FileDto>> resp = fileService.listFiles(in);
        return RespUtil.OK(resp);
    }

    @RequestMapping(value = "deleteFiles",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> deleteFiles(@RequestBody JSONObject json){
        FileDtoIn in = BeanConvertUtil.covertBean(json, FileDtoIn.class);
        Resp<Void> resp = fileService.deleteFiles(in);
        return RespUtil.OK(resp);
    }
}
